'use client'

import { useEffect, useState } from 'react'
import UserTable from '@/app/users/components/UserTable'
import UserForm from '@/app/users/components/UserForm'
import { User } from '@/app/types/user'
import PasswordForm from '@/app/users/components/PasswordForm'

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([])
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [isFormOpen, setIsFormOpen] = useState(false)
  const [isPasswordFormOpen, setIsPasswordFormOpen] = useState(false)
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null)
  const [isResetPassword, setIsResetPassword] = useState(false)

  useEffect(() => {
    fetchUsers()
  }, [])

  const fetchUsers = async () => {
    try {
      const response = await fetch('/api/users')
      const data = await response.json()
      setUsers(data)
    } catch (error) {
      console.error('Failed to fetch users:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleAddUser = async (userData: Omit<User, 'id' | 'createdAt'>) => {
    try {
      const response = await fetch('/api/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(userData),
      })
      const newUser = await response.json()
      setUsers([...users, newUser])
      setIsFormOpen(false)
    } catch (error) {
      console.error('Failed to add user:', error)
    }
  }

  const handleEditUser = async (userData: Omit<User, 'id' | 'createdAt'> | User) => {
    if ('id' in userData) {
      try {
        const response = await fetch(`/api/users/${userData.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(userData),
        })
        const updatedUser = await response.json()
        setUsers(users.map(u => u.id === updatedUser.id ? updatedUser : u))
      } catch (error) {
        console.error('Failed to update user:', error)
      }
    }
    setEditingUser(null)
    setIsFormOpen(false)
  }

  const handleDeleteUser = async (id: string) => {
    try {
      await fetch(`/api/users/${id}`, { method: 'DELETE' })
      setUsers(users.filter(user => user.id !== id))
    } catch (error) {
      console.error('Failed to delete user:', error)
    }
  }

  const handleChangePassword = (userId: string) => {
    setSelectedUserId(userId)
    setIsResetPassword(false)
    setIsPasswordFormOpen(true)
  }

  const handleResetPassword = (userId: string) => {
    setSelectedUserId(userId)
    setIsResetPassword(true)
    setIsPasswordFormOpen(true)
  }

  const [isLoading, setIsLoading] = useState(true)

  if (isLoading) return <div className="text-white">加载中...</div>

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-semibold text-white">用户管理</h1>
        <button
          onClick={() => {
            setEditingUser(null)
            setIsFormOpen(true)
          }}
          className="bg-[#1e3a8a] text-white px-4 py-2 rounded-md hover:bg-[#1e3a8a]/80 transition-colors"
        >
          添加用户
        </button>
      </div>

      <UserTable
        users={users}
        onEdit={(user: User) => {
          setEditingUser(user)
          setIsFormOpen(true)
        }}
        onDelete={handleDeleteUser}
        onChangePassword={handleChangePassword}
        onResetPassword={handleResetPassword}
      />

      {isFormOpen && (
        <UserForm
          user={editingUser}
          onSubmit={editingUser ? handleEditUser : handleAddUser}
          onClose={() => {
            setIsFormOpen(false)
            setEditingUser(null)
          }}
        />
      )}

      {isPasswordFormOpen && selectedUserId && (
        <PasswordForm
          userId={selectedUserId}
          isReset={isResetPassword}
          onClose={() => {
            setIsPasswordFormOpen(false)
            setSelectedUserId(null)
          }}
        />
      )}
    </div>
  )
} 